package com.iflytek.sbd.demo.yinyong;

/**
 * @program: sbd
 * @description: 强引用demo
 * @author: 陈英俊
 * @create: 2022-01-26 09:52
 */
public class StrongReferenceDemo {

    public static int M = 1024*1024;

    public static void printlnMemory(String tag){
        Runtime runtime = Runtime.getRuntime();
        int M = StrongReferenceDemo.M;
        System.out.println("\n"+tag+":");
        System.out.println(runtime.freeMemory()/M+"M(free)/" + runtime.totalMemory()/M+"M(total)");
    }

    public static void main(String[] args){
        StrongReferenceDemo.printlnMemory("1.原可用内存和总内存");

        //实例化10M的数组并与strongReference建立强引用
        byte[] strongReference = new byte[10*StrongReferenceDemo.M];
        StrongReferenceDemo.printlnMemory("2.实例化10M的数组,并建立强引用");
        System.out.println("strongReference : "+strongReference);

        System.gc();
        StrongReferenceDemo.printlnMemory("3.GC后");
        System.out.println("strongReference : "+strongReference);

        //strongReference = null;后,强引用断开了
        strongReference = null;
        StrongReferenceDemo.printlnMemory("4.强引用断开后");
        System.out.println("strongReference : "+strongReference);

        System.gc();
        StrongReferenceDemo.printlnMemory("5.GC后");
        System.out.println("strongReference : "+strongReference);
    }
}
